import { loginApi } from '@/api/user'
import { setToken, getToken, removeToken } from '@/utils/auth'
// import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken('TokenKey'),
    userInfo: getToken('userInfo')
  }
}

const state = getDefaultState()

const mutations = {
  setToken(state, token) {
    state.token = token
    // 并且把token存入缓存
    setToken('TokenKey', token)
  },
  // 把userInfo存入缓存
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
    setToken('userInfo', userInfo)
  },
  // 清除vuex和本地cookie
  logout(state) {
    state.token = null
    state.userInfo = {}
    removeToken('TokenKey')
    removeToken('userInfo')
  }
}

const actions = {
  // 登录
  async login({ commit }, data) {
    const lg = await loginApi(data)
    const token = lg.data.data.token.token
    const userInfo = lg.data.data.user
    commit('setUserInfo', userInfo)
    commit('setToken', token)
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
